<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="优惠券类型" prop="couponType">
        <el-select v-model="dataForm.couponType" class="m-2" placeholder="优惠券类型" size="large" @change="useCouponTypeChange">
          <el-option
            v-for="item in couponTypeOptions"
            :key="item.key"
            :label="item.name"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠卷名字" prop="couponName" :rules="[
        { required: true, message: '优惠卷名字不能为空'}
      ]">
        <el-input v-model="dataForm.couponName" placeholder="优惠卷名字"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="num" :rules="[
            { required: true, message: '数量不能为空'},
            { type: 'number', message: '数量必须为数字值'}
          ]" v-if="dataForm.couponType === 1">
        <el-input v-model.number="dataForm.num" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="金额" prop="amount" :rules="[
            { required: true, message: '金额不能为空'},
            { type: 'number', message: '金额必须为数字值'}
          ]">
        <el-input v-model.number="dataForm.amount" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="每人限领张数" prop="perLimit" :rules="[
            { required: true, message: '每人限领张数不能为空'},
            { type: 'number', message: '每人限领张数必须为数字值'}
          ]">
        <el-input v-model.number="dataForm.perLimit" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="使用门槛金额" prop="minPoint" :rules="[
            { required: true, message: '使用门槛金额不能为空'},
            { type: 'number', message: '使用门槛金额必须为数字值'}
          ]">
        <el-input v-model.number="dataForm.minPoint" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" :rules="[
            { required: true, message: '开始时间不能为空'}
          ]">
        <div class="block">
          <el-date-picker
            v-model="dataForm.startTime"
            align="right"
            type="datetime"
            placeholder="选择日期">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime" :rules="[
            { required: true, message: '结束时间不能为空'}
          ]">
        <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.endTime"></el-date-picker>
      </el-form-item>
      <el-form-item label="使用类型" prop="useType">
        <el-select v-model="dataForm.useType" class="m-2" placeholder="使用类型" size="large" @change="useTypeChange">
          <el-option
            v-for="item in useTypeOptions"
            :key="item.key"
            :label="item.name"
            :value="item.key"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="指定分类" prop="category" v-show="dataForm.useType === 1">
        <el-popover placement="right-end" v-model="popCatelogSelectVisible" width="425">
          <category-cascader :catelogPath.sync="catelogPath" style="width: 400px;"></category-cascader>
          <div style="text-align: right; margin-top: 10px">
            <el-button size="mini" type="text" @click="popCatelogSelectVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="addCatelogCoupon()">确定</el-button>
          </div>
          <el-button slot="reference">添加指定分类</el-button>
        </el-popover>

        <div>
          <el-tag
            style="margin-right: 20px; margin-top: 10px;"
            v-for="item in list"
            :key="item.id"
            type="success"
            closable
            effect="dark"
            @close="handleClose(item, 0)">
            {{ item.name }}
          </el-tag>
        </div>
      </el-form-item>

      <el-form-item label="指定商品" prop="spu" v-show="dataForm.useType === 2">
        <el-popover placement="right-end" v-model="popProductSelectVisible" width="425">
          <el-cascader
            filterable
            clearable
            placeholder="试试搜索：商品名称"
            v-model="paths"
            :options="products"
            :props="setting"
            style="width: 100%;"
          ></el-cascader>
          <div style="text-align: right; margin-top: 10px">
            <el-button size="mini" type="text" @click="popProductSelectVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="addProductCoupon()">确定</el-button>
          </div>
          <el-button slot="reference">添加指定商品</el-button>
        </el-popover>

        <div>
          <el-tag
            style="margin-right: 20px; margin-top: 10px;"
            v-for="item in list"
            :key="item.id"
            type="success"
            closable
            effect="dark"
            @close="handleClose(item, 1)">
            {{ item.name }}
          </el-tag>
        </div>
      </el-form-item>

      <el-form-item label="图片" prop="couponImg" v-show="dataForm.couponType === 1 && dataForm.useType !== 0">
        <div>
          <div
            v-for="item in imageList"
            :key="item"
            style="display: inline-block; border-radius: 5px; width: 104px; height: 104px; margin: 5px;"
            :class="dataForm.couponImg === item ? 'useImageButton' : 'noUseImageButton'"
            @click="dataForm.couponImg = item">
            <el-image
              style="width: 100px; height: 100px; border-radius: 5px;"
              :src="item"
              fit="cover"></el-image>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="备注" prop="note">
        <el-input v-model="dataForm.note" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item label="领取开始日期" prop="enableStartTime" :rules="[
            { required: true, message: '领取开始日期不能为空'}
          ]" v-if="dataForm.couponType !== 0">
        <div class="block">
          <el-date-picker
            v-model="dataForm.enableStartTime"
            align="right"
            type="datetime"
            placeholder="选择日期">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="领取结束日期" prop="enableEndTime" :rules="[
            { required: true, message: '领取结束日期不能为空'}
          ]" v-if="dataForm.couponType !== 0">
        <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.enableEndTime"></el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { info, add, update, getCategoryImage, getSpuImage } from '@/api/coupon/coupon'
import { getSpuAll } from '@/api/goods/spu-info'
import { getCategoryNameByCategoryId } from '@/api/goods/category'
import CategoryCascader from "@/components/Common/category-cascader";

export default {
  data() {
    return {
      visible: false,
      loading: false,
      useTypeOptions: [
        {
          key: 0,
          name: "全场通用"
        },
        {
          key: 1,
          name: "指定分类"
        },
        {
          key: 2,
          name: "指定商品"
        }
      ],
      couponTypeOptions: [
        {
          key: 0,
          name: "后台赠送"
        },
        {
          key: 1,
          name: "自行领取"
        }
      ],
      setting: {
        value: "id",
        label: "spuName"
      },
      products: [],
      paths: this.products,
      popProductSelectVisible: false,
      catelogPath: [],
      popCatelogSelectVisible: false,
      list: [],
      imageList: [],
      spuShowList: [],
      spuList: [],
      dataForm: {
        id: undefined,
        couponType: 0,
        couponImg: "",
        couponName: "",
        num: 0,
        amount: 0,
        perLimit: 0,
        minPoint: 0,
        startTime: "",
        endTime: "",
        useType: 0,
        note: "",
        publishCount: 0,
        useCount: 0,
        receiveCount: 0,
        enableStartTime: "",
        enableEndTime: "",
        code: "",
        memberLevel: "",
        publish: 0
      }
    }
  },
  components: {
    CategoryCascader
  },
  methods: {
    handleClose(item, type){
      this.$delete(this.list, this.list.indexOf(item))
      if(type === 0){
        this.getImageByCategory()
      } else {
        this.getImageBySpu()
      }
    },
    useCouponTypeChange() {
      this.dataForm.enableStartTime = ''
      this.dataForm.enableEndTime = ''
    },
    useTypeChange(){
      this.list = []
      this.imageList = []
      this.dataForm.couponImg = ''
    },
    addProductCoupon(){
      const productId = this.paths[this.paths.length-1]
      let temp = true
      this.list.forEach((item)=>{
        if(item.id === productId){
          temp = false
        }
      })
      if(temp){
        this.popProductSelectVisible = false;
        const product = {}
        product.id = productId
        this.products.forEach((item) => {
          if(this.paths[0] === item.id){
            product.name = item.spuName
            this.list.push(product)
          }
        })
        this.getImageBySpu()
      } else {
        this.$message({
          message: "已经有商品了",
          type: "error"
        });
      }
    },
    addCatelogCoupon(){
      const catelogId = this.catelogPath[this.catelogPath.length-1]
      let temp = true
      this.list.forEach((item)=>{
        if(item.id === catelogId){
          temp = false
        }
      })
      if(temp){
        this.popCatelogSelectVisible =false;
        const catelog = {}
        catelog.id = catelogId
        getCategoryNameByCategoryId(catelogId)
          .then(({data})=>{
            catelog.name = data
            this.list.push(catelog)
            this.getImageByCategory()
          })
          .catch(()=>{})
      } else {
        this.$message({
          message: "已经有分类了",
          type: "error"
        });
      }
    },
    getImageBySpu(){
      const idList = []
      this.list.forEach((item) => {
        idList.push(item.id)
      })
      getSpuImage(idList)
        .then(({data}) => {
          this.imageList = data
        })
        .catch(() => {})
    },
    getImageByCategory(){
      const idList = []
      this.list.forEach((item) => {
        idList.push(item.id)
      })
      getCategoryImage(idList)
        .then(({data}) => {
          this.imageList = data
        })
        .catch(() => {})
    },
    init(id) {
      this.list = []
      this.imageList = []
      this.dataForm.couponImg = ''
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true
          info(this.dataForm.id)
          .then(({ data }) => {
            this.dataForm = data.couponEntity
            this.list = data.couponDTO
            this.loading = false
          });
        }
      });
      this.getSpuInfo()
    },
    getSpuInfo(){
      getSpuAll()
        .then(({data})=>{
          this.products = data
        })
        .catch(()=>{})
    },
    // 表单提交
    dataFormSubmit() {
      if(this.list.length > 0 || this.dataForm.useType === 0){
        if(this.dataForm.couponType === 1 && this.dataForm.useType !== 0){
          if(this.dataForm.couponImg === ''){
            this.$message({
              message: "请选择图片",
              type: "error"
            });
          } else {
            this.submitCoupon(this.list)
          }
        } else {
          this.submitCoupon(this.list)
        }
      }else{
        if(this.dataForm.useType === 1){
          this.$message({
            message: "请指定分类",
            type: "error"
          });
        } else {
          this.$message({
            message: "请指定商品",
            type: "error"
          });
        }
      }

    },
    submitCoupon(list){
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if(!this.dataForm.id){
            add({couponEntity: this.dataForm, couponDTO: list})
              .then(() => {
                this.$message({
                  message: "添加成功",
                  type: "success"
                });
                this.visible = false;
                this.$emit("refreshDataList");
              }).catch(()=>{})
          } else {
            console.log(this.dataForm)
            update({couponEntity: this.dataForm, couponDTO: list})
              .then(() => {
                this.$message({
                  message: "修改成功",
                  type: "success"
                });
                this.visible = false;
                this.$emit("refreshDataList");
              }).catch(()=>{})
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped="scoped">
.useImageButton{
  border: 2px solid #1890ff;
}
.noUseImageButton{
  border: 2px solid rgb(200, 200, 200);
  &:hover{
    cursor: pointer;
  }
}
</style>
